package org.dtrd.modules.archive.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dtrd.config.system.Constant;
import org.dtrd.modules.archive.entity.bean.report.AnamnesisReport;
import org.dtrd.modules.archive.entity.po.DtrdEntRdArchiveAnamnesis;
import org.dtrd.modules.archive.mapper.DtrdEntRdAnamnesisMapper;
import org.dtrd.modules.archive.service.IDtrdEntRdAnamnesisService;
import org.dtrd.modules.system.service.ISysDictService;
import org.dtrd.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.StringJoiner;

/**
 * @author 萧
 * @date 2021-10-01 22:47:26
 **/
@Service
@DS("multi-datasource1")
public class DtrdEntRdAnamnesisServiceImpl extends ServiceImpl<DtrdEntRdAnamnesisMapper, DtrdEntRdArchiveAnamnesis> implements IDtrdEntRdAnamnesisService {

    @Autowired
    private ISysDictService dictService;

    private final static String pubDossierHypoglycemiaCause = "pubDossierHypoglycemiaCause";

    private final static String pubDossierHypoglycemiaSymptom = "pubDossierHypoglycemiaSymptom";

    private final static String pubDossierKetoacidosisCause = "pubDossierKetoacidosisCause";

    private final static String pubDossierKetoacidosisDegree = "pubDossierKetoacidosisDegree";

    private final static String pubDossierKidney = "pubDossierKidney";

    private final static String other = "其他";

    private final static Integer symptom = 2;

    @Override
    public AnamnesisReport getPatientAnamnesisReport(Integer patientId) {
        DtrdEntRdArchiveAnamnesis po = getPatientAnamnesis(patientId);
        // 没数据的时候返回 null 给前端判断
        AnamnesisReport report = null;
        if (po != null) {
            report = new AnamnesisReport().parseFromPO(po);
            Constant.DiabetesDiagnose confirm = Constant.DiabetesDiagnose.DIAGNOSE;
            //region 低血糖史
            Integer hypoglycemiaIsExist = po.getHypoglycemiaIsExist();
            if (hypoglycemiaIsExist != null && hypoglycemiaIsExist.equals(confirm.getType())) {
                report.setHypoglycemiaIsExistText(confirm.getName());
                if (po.getHypoglycemiaFrequency() != null) {
                    report.setHypoglycemiaFrequency(po.getHypoglycemiaFrequency() + "次/年");
                }
                String cause = po.getHypoglycemiaCause();
                if (StrUtil.isNotBlank(cause)) {
                    String text = dictService.queryDictTextByKey(pubDossierHypoglycemiaCause, cause);
                    if (text.equals(other)) {
                        report.setHypoglycemiaCause(po.getHypoglycemiaCauseOther());
                    } else {
                        report.setHypoglycemiaCause(text);
                    }
                }
                Integer ifSymptom = po.getHypoglycemiaIfSymptom();
                if (ifSymptom.equals(symptom)) {
                    String symptoms = po.getHypoglycemiaSymptom();
                    if (StrUtil.isNotBlank(symptoms)) {
                        String dict = dictService.translateCombineDict(symptoms, pubDossierHypoglycemiaSymptom, po.getHypoglycemiaSymptomOther());
                        report.setHypoglycemiaSymptom(dict);
                    }
                } else {
                    report.setHypoglycemiaSymptom("无症状");
                }
            }
            //endregion
            //region 糖尿病酮症酸中毒发生史
            Integer ketoacidosis = po.getKetoacidosis();
            if (ketoacidosis != null && ketoacidosis.equals(confirm.getType())) {
                report.setKetoacidosisText(confirm.getName());
                if (po.getKetoacidosisFrequency() != null) {
                    report.setKetoacidosisFrequency(po.getKetoacidosisFrequency() + "次/周");
                }
                String cause = dictService.queryDictTextByKey(pubDossierKetoacidosisCause, po.getKetoacidosisCause());
                if (StrUtil.isNotBlank(cause)) {
                    if (cause.equals(other)) {
                        report.setKetoacidosisCause(po.getKetoacidosisCauseOther());
                    } else {
                        report.setKetoacidosisCause(cause);
                    }
                }
                Integer ketoacidosisDegree = po.getKetoacidosisDegree();
                if (ketoacidosisDegree != null) {
                    String text = dictService.queryDictTextByKey(pubDossierKetoacidosisDegree, ketoacidosisDegree + "");
                    report.setKetoacidosisDegreeText(text);
                }
                report.setKetoacidosisBloodKetone(po.getKetoacidosisBloodKetone());
                Integer ketone = po.getKetoacidosisUrineKetone();
                if (ketone != null) {
                    report.setKetoacidosisUrineKetoneText(Constant.YinYang.valueOf(ketone).getName());
                }
            }
            //endregion
            //region 其他原因导致肾脏疾病
            Integer kidney = po.getKidney();
            if (kidney != null && kidney.equals(confirm.getType())) {
                report.setKidneyText(confirm.getName());
                report.setKidneyDiseaseDate(po.getKidneyDiseaseDate());
                String disease = po.getKidneyDisease();
                if (StrUtil.isNotBlank(disease)) {
                    String dict = dictService.translateCombineDict(disease, pubDossierKidney, po.getKidneyDiseaseChecksOther());
                    report.setKidneyDisease(dict);
                }
                StringJoiner joiner = new StringJoiner("; ");
                Integer kidneyPro = po.getKidneyPro();
                if (kidneyPro != null) {
                    switch (kidneyPro) {
                        case 1:
                            joiner.add("尿常规（尿蛋白）：阴性");
                            break;
                        case 2:
                            joiner.add("尿常规（尿蛋白）：阳性");
                    }
                }
                if (po.getKidneyAcr() != null) {
                    joiner.add("尿白蛋白/尿肌酐（ACR）：" + po.getKidneyAcr());
                }
                if (po.getKidneyCr() != null) {
                    joiner.add("血清肌酐（Cr）：" + po.getKidneyCr());
                }
                if (po.getKidneyCcr() != null) {
                    joiner.add("内生肌酐清除率（Ccr）：" + po.getKidneyCcr());
                }
                if (po.getKidneyGfr() != null) {
                    joiner.add("肾小球滤过率（GFR）：" + po.getKidneyGfr());
                }
                report.setKidneyData(joiner.toString());
            }
            //endregion
            //region 其他病史
            StringJoiner otherDisease = new StringJoiner("、");
            if (po.getHepaticFailure() != null && po.getHepaticFailure().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("肝衰竭");
            }
            if (po.getMalignantTumor() != null && po.getMalignantTumor().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("恶性肿瘤");
            }
            if (po.getEpilepsy() != null && po.getEpilepsy().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("癫痫");
            }
            if (po.getGlaucoma() != null && po.getGlaucoma().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("青光眼");
            }
            if (po.getCataract() != null && po.getCataract().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("白内障");
            }
            if (po.getCataractAfterOperation() != null && po.getCataractAfterOperation().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("白内障术后");
            }
            if (po.getPcos() != null && po.getPcos().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("多囊卵巢综合征");
            }
            if (po.getSteroidDiabetes() != null && po.getSteroidDiabetes().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("一过性类固醇性糖尿病");
            }
            if (po.getSepticemia() != null && po.getSepticemia().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("败血症");
            }
            if (po.getThromboembolism() != null && po.getThromboembolism().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("血栓栓塞一年内");
            }
            if (po.getThrombosis() != null && po.getThrombosis().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("血栓形成一年内");
            }
            if (po.getChronicLiver() != null && po.getChronicLiver().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("慢性肝病");
            }
            if (po.getSplenectomy() != null && po.getSplenectomy().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("脾切除");
            }
            if (po.getSenileDementia() != null && po.getSenileDementia().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("老年痴呆");
            }
            if (po.getMentalDisorder() != null && po.getMentalDisorder().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("精神障碍");
            }
            if (po.getVisualImpairment() != null && po.getVisualImpairment().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("视力障碍");
            }
            if (po.getMentalRetardation() != null && po.getMentalRetardation().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("智力障碍");
            }
            if (po.getAmputation() != null && po.getAmputation().equals(Constant.YesOrNo.YES.getType())) {
                otherDisease.add("截肢");
            }
            if (otherDisease.length() != 0) {
                report.setOtherDiseaseOther(otherDisease.toString());
            }
            //endregion
        }
        return report;
    }

    @Override
    public DtrdEntRdArchiveAnamnesis getPatientAnamnesis(Integer patientId) {
        LambdaQueryWrapper<DtrdEntRdArchiveAnamnesis> wrapper = Wrappers.lambdaQuery(DtrdEntRdArchiveAnamnesis.class)
                .eq(DtrdEntRdArchiveAnamnesis::getPatientId, patientId)
                .eq(DtrdEntRdArchiveAnamnesis::getIsDel, 0).last(" limit 1 ");
        return getOne(wrapper);
    }

    @Override
    public DtrdEntRdArchiveAnamnesis initEntity(Integer patientId, String reportUrl) {
        DtrdEntRdArchiveAnamnesis entity = new DtrdEntRdArchiveAnamnesis().init();
        entity.setPatientId(patientId);
        return entity;
    }
}
